package com.lujieni.test.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class BlockingServer {


    public static void main(String[] args) throws IOException {

        ByteBuffer bb = ByteBuffer.allocate(16);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8081));
        List<SocketChannel> list = new ArrayList<>();


        while (true){
            SocketChannel channel = ssc.accept();
            list.add(channel); // blocking the thread until a new connection comes
            for (int i = 0; i < list.size(); i++) {
                list.get(i).read(bb); // blocking the thread until the channel has data to read
                bb.flip(); // change read mode
                CharBuffer content = StandardCharsets.UTF_8.decode(bb);
                System.out.println(content);
                bb.compact(); // change write mode
            }
        }
    }
}
